package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户关注行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {
        //1.参数校验
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取登录用户id
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            //表示未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行此操作
        if (user.getId() == 0) {
            return ResponseResult.okResult(405,"游客身份不能进行此操作");
        }

        //2.用户是否已关注
        //定义关注的 key
        String follow_key="USER_FOLLOW_"+user.getId();
        //定义粉丝的 key
        String fans_key="USER_FANS_"+dto.getAuthorId();
        //判断hash中的大key中的小key中是否包含，如果包含，则返回true,否则false
        boolean followkeyFlag=redisTemplate.opsForHash().hasKey(follow_key,dto.getAuthorId()+"");
        //2.1 用户已经关注了，并且此时要执行关注操作 operation=0，直接返回
        if (followkeyFlag && dto.getOperation()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //2.2 用户已经关注，则此时是取消关注操作,operation=1,删除redis和mongo
        if (followkeyFlag && dto.getOperation()==1){
            //1.删除redis中两个hash
            redisTemplate.opsForHash().delete(follow_key,dto.getAuthorId()+"");
            redisTemplate.opsForHash().delete(fans_key,user.getId()+"");
            //2.删除mongo中的数据
            Query query=Query.query(Criteria.where("userId").is(user.getId()).and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
        }

        //2.3 用户没有关注，并且此时执行的是关注操作 operation=0,新增数据到redis和mongo中
        if (!followkeyFlag && dto.getOperation()==0){
            //1.新增redis,两个hash
            redisTemplate.opsForHash().put(follow_key,dto.getAuthorId()+"","1");
            redisTemplate.opsForHash().put(fans_key,user.getId()+"","1");
            //2.新增mongo数据
            ApFollowBehavior apFollowBehavior=new ApFollowBehavior();
            apFollowBehavior.setId(ObjectId.get().toHexString());
            apFollowBehavior.setUserId(user.getId().longValue());
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setArticleId(dto.getArticleId());
            mongoTemplate.insert(apFollowBehavior);
        }
        return ResponseResult.okResult("关注成功");
    }
}
